/*
 * @Author: 郭招娣 10615594+guo-zhaodi@user.noreply.gitee.com
 * @Date: 2022-10-16 18:56:43
 * @LastEditors: 郭招娣 10615594+guo-zhaodi@user.noreply.gitee.com
 * @LastEditTime: 2022-10-21 19:44:45
 * @FilePath: \实训二——宏业找房\app\demo\src\page\Housing\index.jsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import React, { useState, useEffect } from 'react'
import { Table, Space, Radio, Switch, Popconfirm, message, Button, Modal, Input, Pagination, Select, Drawer } from 'antd';
import './index.css'
import { httpGetHousing, httpDelHousing, httpAddHousing, httpEditHousing, httpGetAgent, httpSetAgents, httpChangeHousingState } from '../../api/index'
import { PropertySearch } from '../../components'
const Housing = () => {
  const { Option } = Select;

  // 抽屉
  const [open, setOpen] = useState(false);
 
  // 房源数据
  const [data, setData] = useState([]);
  const [agent, setAgentData] = useState([])//经纪人数据
  // 状态
  const [state, setState] = useState('')
  // 获取按钮组值
  const [mode, setMode] = useState('销售楼盘')
  // 弹框
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [agentOpen, setAgentOpen] = useState(false);//指定经纪人弹框
  // 添加
  const [name, setName] = useState('')
  const [address, setAddress] = useState('')
  const [price, setPrice] = useState(1)
  const [status, setStatus] = useState(false)
  const [manager, setManager] = useState('')

  // 三级城市
  const [one, setOne] = useState('')//省
  const [two, setTwo] = useState('')//市
  const [three, setThree] = useState('')//区
  const [four, setFour] = useState('')//楼区名称


  const [pageCode, setPageCode] = useState(1);
  const [pageSize, setPageSize] = useState(4);
  const [total, setTotal] = useState(0);
  const [isText, setIsText] = useState(true); //add/edit
  const [agents,setAgents]=useState('')//指派经纪人
  const [editId, setEditId] = useState('') //编辑id
  const [agentId, setAgentId] = useState('') //经纪人id
  //  //跳详情 抽屉弹框
  const showDrawer = (obj) => {
    setOpen(true);
    setName(obj.name)
    setAddress(obj.address)
    setPrice(obj.price)
    setManager(obj.manager)
  };
  const onClose = () => {
    setOpen(false);
  };
  // 编辑添加弹框
  const showModal = (type, obj) => {
    setIsText(type)
    setIsModalOpen(true);
    // 添加
    if (type) {
      setName('')
      setAddress('')
      setPrice('')
      setManager('')
      setStatus('')

      // form.setFieldsValue({
      //   title: '',
      //   address: '',
      //   price: '',
      //   audit: ''
      // });
      // console.log(isText)
    } else {
      // 编辑
      console.log(obj)
      setName(obj.name)
      setAddress(obj.address)
      setPrice(obj.price)
      setManager(obj.manager)
      setEditId(obj.id)
      // form.setFieldsValue({
      //   title: obj.title,
      //   address: obj.address,
      //   price: obj.price,
      //   audit: obj.audit
      // });

    }
  };
  // 指定经纪人弹框
  const agentModal = (record) => {
    setAgentId(record.id)
    setAgentOpen(true);
  }
  // 指定经纪人确定按钮
  const AgentOkModal = async() => {
    console.log(agents.value,'ooo')
    const res = await httpSetAgents('/agents', { id:agentId, agents:agents.value});
    console.log(res,'lll')
    getData()
    setAgentOpen(false)
    message.success(res.data.msg);

    
  };
  // 指定经纪人弹框关闭
  const CancelAgentModal = () => {
    setAgentOpen(false)
  };
  // 编辑添加确认按钮
  const handleOk = async () => {
    if (isText) {
      // 添加
      const res = await httpAddHousing('/add', { name, address, price, status, manager, pageCode, pageSize })
      if (res.data.code === 200) {
        getData();
        message.success(res.data.msg);
      } else {
        message.warning(res.data.msg);
      }
    } else {
      // 编辑
      const res = await httpEditHousing('/edit', { name, address, price, status, manager, pageCode, pageSize, editId })
      if (res.data.code === 200) {
        getData();
        message.success(res.data.msg);
      } else {
        message.warning(res.data.msg);
      }
    }
    setIsModalOpen(false);
  };

  // 编辑添加弹框关闭
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  useEffect(() => {
    getData()
    getAgent()
  }, [one, two, three, four, pageCode])

  // 搜索
  const getValueFromSon = (param) => {
    console.log(param, 'ggg')
    setOne(param.one)
    setTwo(param.two)
    setThree(param.three)
    setFour(param.four)
  }
  // 获取房源数据
  const getData = async () => {
    const res = await httpGetHousing('/housing', { one, two, three, four, pageCode, pageSize });
    setData(res.data.list)
    setTotal(res.data.total)

  }
  // 获取经纪人名单数据
  const getAgent = async () => {
    const res = await httpGetAgent('/agent');
    console.log(res)
    setAgentData(res.data.list)
  }
  // 下拉框选项
  const handleChange = async(value) => {
    setAgents(value)
    // console.log(value)
  }
  // tab切换改变销售还是租赁
  const changeState = (e) => {
    setMode(e.target.value)
    if (mode === '销售楼盘') {
      setState(true)
    } else {
      setState(false)
    }


  }
  // 删除
  const handleDelete = async (id) => {
    const res = await httpDelHousing("/del", { id })
    if (res.status === 200 && res.data.code === 200) {
      message.success(res.data.msg);
      getData()
    } else {
      message.warning(res.data.msg);
    }

  }

  // page页码改变
  const onPageChange = (page) => {
    setPageCode(page)
  };
  // 状态改变
  const onState = async (status, id) => {
    console.log(status, id);
    const res = await httpChangeHousingState('/changeHousingStatus', { status, id });
    getData()
    message.success(res.data.msg);

  }
 
 
  const columns = [
    {
      title: '序号',
      width: 30,
      dataIndex: 'id',
      key: 'id',
      fixed: 'left',
      render: (_, record, index) => (
        <span>{(pageCode-1)*pageSize + index + 1}</span>
      ),
    },
    {
      title: '楼盘名称',
      width: 60,
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '详细地址',
      width: 90,
      dataIndex: 'address',
      key: 'address',
    },
    {
      title: '价格',
      width: 40,
      dataIndex: 'price',
      key: 'price',
    },
    {
      title: '排序',
      width: 20,
      dataIndex: 'sort',
      key: 'sort',
    },
    {
      title: '更新时间',
      width: 80,
      dataIndex: 'updateTime',
      key: 'updateTime',
    },
    {
      title: '状态',
      width: 50,
      dataIndex: 'status',
      key: 'status',
      render: (_, { status, id }) => (
        <div>
          {state ?
            <Switch 
            checkedChildren="开启" 
            unCheckedChildren="关闭"
            checked={status === 'true'}
            onChange={() => onState(status, id)}
           />
            :
            <div></div>
          }
        </div>
      )
      // render: (_, { status, id }) => (
      //   <div>

      //     <Switch
      //       checkedChildren="开启"
      //       unCheckedChildren="关闭"
      //       checked={status === 'true'}
      //       onChange={() => onState(status, id)}
      //     />

      //   </div>
      // )
    },
    {
      title: '经纪人',
      width: 30,
      dataIndex: 'manager',
      key: 'manager',
    },
    {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      width: 90,
      render: (_, record) => (
        <Space size="middle">
          <a onClick={() => showDrawer( record)}>详情</a>
          <a onClick={() => showModal(false, record)}>编辑</a>
          <Popconfirm title="确定删除吗?" onConfirm={() => handleDelete(record.id)}>
            <a>删除</a>
          </Popconfirm>
          <a onClick={() => agentModal(record)}>指派经纪人</a>
        </Space>
      ),
    },
  ];

  // 编辑  另一种
  // const handleEdit = (record)=>{
  //   setIsModalOpen(true);
  //   setIsAdd(false);
  //   console.log(isAdd,1)

  // }
  // // 添加
  // const handleAdd = () => {
  //   setIsModalOpen(true);
  //   setIsAdd(true);
  //   console.log(isAdd,5)
  // }

  return (
    <div>
      <div className='top'>
        <Radio.Group style={{ margin: '10px' }} onChange={changeState} value={mode} defaultChecked={true}>
          <Radio.Button value="销售楼盘" >销售楼盘</Radio.Button>
          <Radio.Button value="房屋租赁">房屋租赁</Radio.Button>
        </Radio.Group>
        {/* 城市三级联动 */}
        <div style={{ display: 'flex' }}>
          <PropertySearch sendValueToFather={getValueFromSon.bind(this)} />

        </div>
        {/* 添加按钮 */}
        <Button type="primary" onClick={() => showModal(true)} style={{ margin: '10px' }}>
          添加
        </Button>
      </div>
      <Table
        columns={columns}
        dataSource={data}
        rowKey="id"
        pagination={false}
      />
      {/* 分页 */}
      <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
        <Pagination current={pageCode} total={total} pageSize={pageSize} onChange={onPageChange} />
      </div>
      {/* 弹框 */}

      <Modal title={isText ? '添加' : '编辑'} open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        <p>
          楼盘名称: <Input style={{ width: '250px' }} value={name} onChange={(e) => setName(e.target.value)} />
        </p>
        <p>详细地址: <Input style={{ width: '250px' }} value={address} onChange={(e) => setAddress(e.target.value)} /></p>
        <p>价格: <Input style={{ width: '250px' }} value={price} onChange={(e) => setPrice(e.target.value)} /></p>
        <p>经纪人: <Input style={{ width: '250px' }} value={manager} onChange={(e) => setManager(e.target.value)} /></p>
      </Modal>

      <Modal title="Basic Modal" open={agentOpen} onOk={AgentOkModal} onCancel={CancelAgentModal}>
        <Select
          labelInValue
          defaultValue={{
            value: '请选择经纪人',
          }}
          style={{
            width: 180,
          }}
          onChange={handleChange}
        >
          {
            agent && agent.map((item, index) => {
              return (
                <Option value={item.name} key={index}>{item.name}</Option>
              )
            })
          }
        </Select>

      </Modal>
          {/* 抽屉 */}
      <Drawer title="详情" placement="right" onClose={onClose} open={open}>
        <p>
          楼盘名称: <Input style={{ width: '250px' }} value={name} onChange={(e) => setName(e.target.value)} />
        </p>
        <p>详细地址: <Input style={{ width: '250px' }} value={address} onChange={(e) => setAddress(e.target.value)} /></p>
        <p>价格: <Input style={{ width: '250px' }} value={price} onChange={(e) => setPrice(e.target.value)} /></p>
        <p>经纪人: <Input style={{ width: '250px' }} value={manager} onChange={(e) => setManager(e.target.value)} /></p>
      </Drawer>
    </div>
  )
}
export default Housing;